package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.contants.MessageConstant;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.ex.CustomerException;
import com.itheima.reggie.service.EmployeeService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Objects;

/**
 * 员工控制层
 */
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * 登录
     *
     * @param session
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public R login(HttpSession session, @RequestBody Employee employee) {
        //①. 将页面提交的密码password进行md5加密处理, 得到加密后的字符串
        String password = employee.getPassword();
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());

        //②. 根据页面提交的用户名username查询数据库中员工数据信息
        Employee emp = employeeService.getOne(Wrappers.<Employee>lambdaQuery().eq(Employee::getUsername, employee.getUsername()));

        //③. 如果没有查询到, 则返回登录失败结果
        if (emp == null) {
            throw new CustomerException(MessageConstant.EMPLOYEE_USERNAME_NOTEXIST);
        }

        //④. 密码比对，如果不一致, 则返回登录失败结果
        if (!emp.getPassword().equals(md5Password)) {
            throw new CustomerException(MessageConstant.EMPLOYEE_USERNAME_PASSWORD_ERROR);
        }

        //⑤. 查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        if (!emp.getStatus().equals(1)) {
            throw new CustomerException(MessageConstant.EMPLOYEE_STATUS_ERROR);
        }
        //⑥. 登录成功，将员工id存入Session, 并返回登录成功结果
        session.setAttribute("employee", emp.getId());
        emp.setPassword("");
        return R.success(emp);
    }

    /**
     * 退出登录
     *
     * @param session
     * @return
     */
    @PostMapping("/logout")
    public R logout(HttpSession session) {
        session.removeAttribute("employee");
        return R.success(MessageConstant.EMPLOYEE_EXIT_SUCCESS);
    }

    /**
     * 添加员工
     *
     * @param session
     * @param employee
     * @return
     */
    @PostMapping
    public R add(HttpSession session, @RequestBody Employee employee) {
        Long employeeId = (Long) session.getAttribute("employee");
        return employeeService.add(employee, employeeId);
    }

    /**
     * 分页查询员工
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R page(Integer page, Integer pageSize, String name) {
        Page<Employee> iPage = new Page<>(page, pageSize);

        // 分页查询条件
        LambdaQueryWrapper<Employee> lqw = Wrappers.lambdaQuery();
        lqw.select(Employee.class,i -> !i.getColumn().equals("password"));
        lqw.like(StringUtils.isNotBlank(name), Employee::getName, name);
        lqw.orderByDesc(Employee::getUpdateTime);

        // 分页查询
        employeeService.page(iPage, lqw);

        return R.success(iPage);
    }

    /**
     * 修改员工信息
     *
     * @param employee
     * @return
     */
    @PutMapping
    public R editStatus(HttpSession session, @RequestBody Employee employee) {
        Long adminId = (Long) session.getAttribute("employee");

        return employeeService.modifyEmp(employee,adminId);
    }

    @GetMapping("/{id}")
    public R findById(@PathVariable Long id) {
        // 校验数据
        if (Objects.isNull(id)) {
            throw new CustomerException(MessageConstant.PARAM_ERROR);
        }
        // 根据id查询用户
        Employee employee = employeeService.getOne(Wrappers.<Employee>lambdaQuery().eq(Employee::getId, id));
        if (Objects.isNull(employee)) {
            throw new CustomerException(MessageConstant.EMPLOYEE_SELECT_ERROR);
        }

        return R.success(employee);
    }
}